class JankenService {
    static scope = "session"
    boolean transactional = false
    def gameOver = false
    def playerScore = 0
    def opponentScore = 0
    /*
     * return -1 if one wins, 1 if two wins and 0 if draw
     */
    int fair(Janken one, Janken two) {
        def result = one.point - two.point
        switch(result){
            case -2:
                return -1
            case -1:
                return 1
            case 0:
                return 0
            case 1:
                return -1
            case 2:
                return 1
        }
    }

    def play(Janken player, Janken opponent){
        if(!gameOver){
            def winner = fair(player, opponent)
            if(winner == -1){
                playerScore++
            }else if(winner == 1){
                opponentScore++
            }
            if(playerScore >= 2){
                gameOver = true
                return "player"
            } else if(opponentScore >= 2){
                gameOver = true
                return "opponent"
            }
            return null
        }else{
            throw new IllegalStateException("Game is over")
        }
    }

    def restart(){
        gameOver = false
        playerScore = 0
        opponentScore = 0
    }
}
